\section{Python Scripting}

\centeredlargetext{white}{black}{
Python Scripting
}

\subsection{Using Spyder}

\begin{frame}[fragile]
\frametitle{Launch the Spyder IDE}
\overlayicon{Icons/spyder}
\setlength\fboxsep{1pt}
\definecolor{darkred}{rgb}{0.75,0.25,0.25}
\begin{itemize}
  \item So far we've been interacting with an interpreter. \\
        How do we write a script?
  \item Open the Spyder IDE by clicking \fcolorbox{black}{darkred}{\includegraphics[height=1.5em]{Icons/spyder}} in the launcher.
  \pause
  \item Note: This version of Spyder (2.1.9) does not fully integrate with the installed version of IPython (0.12).
  \begin{itemize}
    \item The standard Python shell in Spyder has been enhanced with some features of IPython, like tab completion.
    \item IPython will run within Spyder, but certain capabilities, like plotting, do not work.
    \item IPython integration is scheduled to be fixed in Spyder 2.2, planned for October 2012.
    \item For now we will use the standard interpreter, the one with the \pyprompt prompt.
  \end{itemize}
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Using the Spyder IDE}
\overlayicon{Icons/spyder}
\begin{itemize}
  \item Spyder has an editor, interpreter, variable explorer, object inspector \ldots
\end{itemize}
\begin{center}
\includegraphics[width=0.8\paperwidth]{ScreenShot/spyder}
\end{center}
\end{frame}


\subsection{Hello World Script}

\begin{frame}[fragile]
\frametitle{Hello World}
\begin{itemize}
\item The simple way
\end{itemize}
\begin{lstlisting}
print "Hello World"
\end{lstlisting}
\begin{itemize}
\pause
\item Note: In Python 3 \lstpy{print} is a function, not a statement.
\end{itemize}
\begin{lstlisting}
print("Hello World")  # Python 3 version
\end{lstlisting}
\begin{itemize}
\pause
\item A more complete example
\vspace{-3mm}
\end{itemize}
\lstset{title=Examples/HelloWorld.py}
\lstlistingwithnumber{1}{15}{Examples/HelloWorld.py}
\end{frame}

\begin{frame}
\frametitle{Hello World: line-by-line}
\begin{itemize}
\item Comments.  The first line is a shebang directive for Unix.
\lstlistingwithnumber{1}{2}{Examples/HelloWorld.py}
\pause
\item Documentation string (docstring) for the script.  Uses triple quotes.
\lstlistingwithnumber{5}{5}{Examples/HelloWorld.py}
\pause
\item Assigns the ``Hello World'' string to a global variable.
\lstlistingwithnumber{7}{7}{Examples/HelloWorld.py}
\pause
\item A function definition with docstring.
It calls the print function.
\lstlistingwithnumber{9}{11}{Examples/HelloWorld.py}
\pause
\item Call the main function only if this file is run as a script (not imported).
\lstlistingwithnumber{14}{15}{Examples/HelloWorld.py}
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Running a Script}
\begin{columns}[c]
\column{0.6\textwidth}
\begin{itemize}
  \item In Spyder run the active script with \\
        Menu ``Run$\rightarrow$Run'', or press F5
  \item Adjust the configuration settings and press the ``Run'' button
  \item Future runs use the same configuration
  \item Change the run configuration with\\
        Menu ``Run$\rightarrow$Configure'', or press F6
\end{itemize}
\column{0.36\textwidth}
\includegraphics[width=\textwidth]{ScreenShot/spyder_run}
\end{columns}
\pause
\begin{itemize}
  \item Alternatively, in a terminal window (from the home directory) run
        \verb|python Tutorial/Examples/HelloWorld.py|
\end{itemize}
\end{frame}


\subsection{Language Constructs}


\begin{frame}[fragile]
\frametitle{Conditionals}

\vspace{-1em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
if a > 10
    a = 10;
end
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
if a > 10:
    a = 10
\end{pythonBlock}
\end{columns}

\begin{itemize}
\item Syntax of basic conditionals is very similar.
\item MATLAB uses keyword \lstmat{end} to designate the end of a block.
\item Python uses \lstpy{:} to start a block and indentation to designate duration.
  \begin{itemize}
  \item These rules apply generally to loops, functions, classes, etc.
  \item \textbf{Indentation is important in Python!}
  \item Choose any indentation, but consistent indentation defines a block.
  \end{itemize}
\end{itemize}
\pause
\vspace{-2em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
if a > 10
    disp('a greater than 10')
elseif a < 5
    disp('a less than 5')
else
    disp('a is ', a)
end
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
if a > 10:
    print 'a greater than 10'
elif a < 5:
    print 'a less than 5'
else:
    print 'a is', a
\end{pythonBlock}
\end{columns}
\begin{itemize}
 \item Note, \lstmat{elseif} in MATLAB becomes \lstpy{elif} in Python.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Loops}

\vspace{-1em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
x = 1;
while x < 10
    x = x * 2;
end
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
x = 1
while x < 10:
    x = x * 2
\end{pythonBlock}
\end{columns}
\begin{itemize}
\item MATLAB and Python \lstpy{while} loops are essentially the same.
\item \lstpy{break} and \lstpy{continue} statements are the same in both languages.
\end{itemize}
\pause

\vspace{-1em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
X = [5 4 3 2 1];
for v = X
    disp(v)
end
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
X = [5, 4, 3, 2, 1]
for v in X:
    print v
\end{pythonBlock}
\end{columns}

\begin{itemize}
\item MATLAB and Python \lstpy{for} loops each iterate over a container.
\item MATLAB uses symbol \lstmat{=} while Python uses keyword \lstpy{in}.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Generating Ranges}
\begin{itemize}
\item MATLAB has special syntax to generate a range of numbers
  \begin{itemize}
  \item \lstmat{first:last}
  \item \lstmat{first:step:last}
  \end{itemize}
\item Python use the \lstpy{range} function to achieve similar behavior
  \begin{itemize}
  \item \lstpy{range(end)}
  \item \lstpy{range(first, end)}
  \item \lstpy{range(first, end, step)}
  \end{itemize}

\end{itemize}
\vspace{-1em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
> 0:4
 0  1  2  3  4
> 2:5
 2  3  4  5
> 6:-2:2
 6  4  2
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
> range(5)
[0, 1, 2, 3, 4]
> range(2, 6)
[2, 3, 4, 5]
> range(6, 1, -2)
[6, 4, 2]
\end{pythonBlock}
\end{columns}

\begin{itemize}
\item Note that \lstmat{last} is inclusive while \lstpy{end} is not.
In MATLAB  \lstmat{first}$\leq i \leq$\lstmat{last}, but in Python \lstpy{first}$\leq i <$\lstpy{end}.
\item Python's \lstpy{range} function is limited to integer types.
NumPy adds the \lstpy{arange} function which generalizes to floats.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Defining Functions}

\vspace{-1em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
function [s, d] = sum_diff(x, y)
% SUM_DIFF Sum and diff of two values.
% x is the first value
% y is the second value

s = x + y;
d = x - y;
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
def sum_diff(x, y):
    """Sum and diff of two values.

    x is the first value
    y is the second value
    """
    return x + y, x - y
\end{pythonBlock}
\end{columns}
\pause
\begin{itemize}
\item MATLAB handles return values by explicitly naming them.
  \begin{itemize}
  \item returns zero, one, or multiple named variables.
  \end{itemize}
\pause
\item Python always returns exactly one object with the \lstpy{return} statement.
  \begin{itemize}
  \item a standalone or missing \lstpy{return} statement returns \lstpy{None}.
  \item returning multiple comma-separated objects (as above) returns a tuple.
  \end{itemize}
\end{itemize}
\pause
\vspace{-2em}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
> [v1, v2] = sum_diff(7, 4)
v1 = 11
v2 = 3
> v3 = sum_diff(7, 4)
v3 = 11
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
> v1, v2 = sum_diff(7, 4)
> v3 = sum_diff(7, 4)
> print "v1 = ", v1, ", v2 = ", v2, \
        ", v3 = ", v3
v1 = 11, v2 = 3, v3 = (11, 3)
\end{pythonBlock}
\end{columns}
\end{frame}


\begin{frame}[fragile]
\frametitle{Defining Functions -- Optional Arguments}
\reference{
\url{http://docs.python.org/tutorial/controlflow.html\#keyword-arguments}
}
\begin{itemize}
  \item MATLAB function arguments are all optional, but you can enforce the number of arguments and set default values by checking \lstmat{nargin}.
  \item Python function arguments are required unless a default value is specified.
  \item All optional arguments must come after all required arguments.
\end{itemize}
\vspace{-5mm}
\begin{columns}[t]
\column{0.45\textwidth}
\begin{matlabBlock}
function val = my_func(req, opt1, opt2)
if nargin < 3
    opt2 = 'default string';
elseif nargin < 2
    opt1 = 3.14;
end
disp(opt2)
val = req * opt1
\end{matlabBlock}
\column{0.45\textwidth}
\begin{pythonBlock}
def my_func(req, opt1=3.14,
            opt2='default string'):
    print opt2
    return req * opt1
\end{pythonBlock}
\end{columns}
\begin{itemize}
  \item Python optional arguments can be omitted and/or specified as \lstpy{key=value} pairs in any order,
        e.g in the above example \\
        \lstpy{my_func(1, 3.14, 'hi')} is the same as \lstpy{my_func(1, opt2='hi')}
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Managing Libraries of Functions}
\begin{itemize}
  \item MATLAB and Python have different strategies for organizing and calling libraries of functions.
  \pause
  \item In MATLAB, importing functions is implicit.
  \begin{itemize}
    \item Each function must reside in a file of the same name.
    \item When a function is called, the MATLAB path is searched to find the first matching function.
    \item Dealing with functions in different packages with the same name is problematic.
  \end{itemize}
  \pause
  \item In Python, importing functions is explicit.
  \begin{itemize}
    \item Any number of functions can reside in a file.
    \item Modules, packages, and function must be explicitly imported when needed.
    \item Name spaces and renaming allows for easy resolution of name conflicts.
  \end{itemize}
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{Importing Packages, Modules, Functions, etc.}
\reference{
\url{http://docs.python.org/tutorial/modules.html}
}
\begin{itemize}
  \item The Python \lstpy{import} statement is used to explicitly import packages,
        modules, classes, functions, and variables.
  \begin{description}
    \item[module] is a python file (\texttt{.py}) that may contain multiple functions,
                  variables, and classes.
    \item[package] is a collection of modules in a directory.
                   The directory must contain a file named \texttt{\_\_init\_\_.py}.
                   Packages can be nested.
  \end{description}
  \pause
  \item The \lstpy{import} statement initializes a module or package by executing the
        code in the module or \texttt{\_\_init\_\_.py}.
  \item Python searches current directory and Python path to find matching modules and packages.
  \item Each module or package is imported \textbf{only once} in a Python session,
        call \lstpy{reload()} to force reloading.
\end{itemize}
\end{frame}


\begin{frame}[fragile]
\frametitle{An Example Python Package}
\reference{
\url{http://docs.python.org/tutorial/modules.html}
}
\begin{block}{Directory structure of a Python package}
\begin{verbatim}
vision/                         Top-level package
       __init__.py              Initialize vision package
       learning/                Subpackage for learning
                __init__.py
                adaboost.py
                svm.py
       tracking/                Subpackage for tracking
                __init__.py
                kalman.py
       features/                Subpackage for features
                __init__.py
                sift.py
                harris.py
                canny.py
\end{verbatim}
\end{block}
\end{frame}


\begin{frame}[fragile]
\frametitle{Importing Modules and Packages}
\reference{
\url{http://docs.python.org/tutorial/modules.html}
}
\begin{itemize}
  \item If the \texttt{vision} directory is in the Python path then the following works.
\end{itemize}
\begin{lstlisting}
import vision.tracking.kalman          # executes vision/tracking/kalman.py
vision.tracking.kalman.predict()       # call a function in kalman.py
\end{lstlisting}
\pause
\begin{itemize}
  \item Generally \texttt{\_\_init\_\_.py} includes statements to import
        all the sub-packages or modules recursively.
        So the following usually works, but it imports the whole vision package.
\end{itemize}
\begin{lstlisting}
import vision                          # executes vision/__init__.py
vision.features.harris.detect()        # call a function in harris.py
vision.tracking.kalman.predict()       # call a function in kalman.py
\end{lstlisting}
\pause
\begin{itemize}
  \item The \lstpy{as} keyword allows renaming during import.
\end{itemize}
\begin{lstlisting}
import vision.tracking.kalman as kf
kf.predict()
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{Importing Specific Functions or Variables}
\reference{
\url{http://docs.python.org/tutorial/modules.html}
}
\begin{itemize}
  \item The \lstpy{from} keyword allows importing into the current name space.
\end{itemize}
\begin{lstlisting}
from vision.tracking.kalman import predict, correct
predict()
correct()
\end{lstlisting}
\pause
\begin{itemize}
  \item Rename specific functions with \lstpy{as}.
\end{itemize}
\begin{lstlisting}
from vision.tracking.kalman import predict as my_pred, correct as my_corr
my_pred()
my_corr()
\end{lstlisting}
\pause
\begin{itemize}
  \item Using \lstpy{*} imports of everything into the current name space.
\end{itemize}
\begin{lstlisting}
from vision.tracking.kalman import *
predict()
correct()
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
\frametitle{The Python Path}
\reference{
\url{http://docs.python.org/tutorial/modules.html}
}
\begin{itemize}
  \item The Python path is set with environment variable \texttt{PYTHONPATH}.
  \item Modify \lstpy{sys.path} to make temporary changes during execution.
\end{itemize}
\begin{lstlisting}
(*@\ipyprompt@*) import sys

(*@\ipyprompt@*) sys.path.append("/home/tutorial")

(*@\ipyprompt@*) sys.path
(*@\ipyreturn@*)
['',
 '/usr/bin',
 '/usr/lib/python2.7',
 ...
 '/usr/lib/python2.7/dist-packages/IPython/extensions',
 '/home/tutorial']

\end{lstlisting}
\end{frame}

\subsection{Exercise 1}

\begin{frame}[fragile]
\frametitle{Exercise 1}
\framesubtitle{Basic Python}
\begin{itemize}
  \item Open the file \verb|Exercises/ex1.py|
  \item Write the missing function \lstpy{sqrt_dict} to compute a dictionary mapping
        the first \lstpy{n} integers to the square roots of their values.
  \item Hint: use the \lstpy{sqrt} function from the \lstpy{math} module.
  \pause
  \item This example uses \lstpy{sys.argv} to access a list of command line arguments.
\end{itemize}
\lstset{title=Exercises/ex1.py}
\lstlistingwithnumber{19}{28}{Exercises/ex1.py}
\end{frame}


\begin{frame}[fragile]
\frametitle{Exercise 1: Answer}
\framesubtitle{Basic Python}
\begin{itemize}
  \item Here is one possible answer
\end{itemize}
\lstset{title=Exercises/Answers/ex1-answer.py}
\lstlistingwithnumber{6}{15}{Exercises/Answers/ex1-answer.py}
\pause
\begin{itemize}
  \item An alternate one-line solution uses
        \href{http://docs.python.org/tutorial/datastructures.html\#list-comprehensions}
             {list comprehensions}
\end{itemize}
\lstlistingwithnumber{22}{22}{Exercises/Answers/ex1-answer.py}
\end{frame}
